/**
 * 企业微信相关的工具方法
 */
// import axios from 'axios'
// import { applicationInfoData } from '@/api/work-weixin'
import { setLocalStorage, getLocalStorage } from '@/utils'
// import router from '@/router'

export const generateOAuthURL = function (loginState, corpId, agentId, retry = false) {

  const redirect = filterUrlParams()

  return [
    'https://open.weixin.qq.com/connect/oauth2/authorize?',
    [
      `appid=${corpId}`,
      `agentid=${agentId}`,
      `redirect_uri=${redirect}`,
      'response_type=code',
      'scope=snsapi_privateinfo',
      `state=${loginState}`,
      retry ? 'retry=yes' : null
    ]
      .filter(q => !!q)
      .join('&'),
    '#wechat_redirect'
  ].join('')
}

export const random = length => {
  const dict = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let str = ''
  for (let i = 0; i < length; i += 1) {
    str += dict[Math.floor(Math.random() * dict.length)]
  }
  return str
}

/**
 * 获取企微扫码登录授权
 * https://work.weixin.qq.com/api/doc/90000/90135/91019
 * @param state
 * @param corpId
 * @param agentId
 */
export const getQrConnectAuthUrl = (state, corpId, agentId) => {
  return [
    'https://open.work.weixin.qq.com/wwopen/sso/qrConnect?',
    [
      `appid=${corpId}`,
      `agentid=${agentId}`,
      `redirect_uri=${encodeURIComponent(window.location.href.split('#')[0])}`,
      `state=${state}`
    ].join('&')
  ].join('')
}

/**
 * 企业微信官方提供的 ua
 * iPhone:Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89 wxwork/2.2.0 MicroMessenger/6.3.2
 * Android:Mozilla/5.0 (Linux; Android 7.1.2; g3ds Build/NJH47F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043508 Safari/537.36 wxwork/2.2.0 MicroMessenger/6.3.22 NetType/WIFI Language/zh
 * Windows:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36 wxwork/2.1.3 (MicroMessenger/6.2) WindowsWechat QBCore/3.43.644.400 QQBrowser/9.0.2524.400
 * Mac:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) wxwork/2.2.0 (MicroMessenger/6.2) WeChat/2.0.4
 */
const is = regexp => () => {
  return regexp.test(window.navigator.userAgent)
}

/* 是否是企业微信内置浏览器 */
export const isWxWork = is(/wxwork/)

/** 判断是否为移动端 */
export const isMobile = is(/iPhone|Android/)

/** 判断是不是windows */
export const isWindows = is(/Windows/)

/**
 * 重定向
 */
export const redirectLink = ({ corpId, agentId }) => {
  const loginState = random(16)
  setLocalStorage('loginState', loginState)
  // setLocalStorage('sfa_redirect_hash', window.location.hash)
  // console.log('isWxWork:', isWxWork())
  if (!isWxWork()) {
    // 非企业微信浏览器打开
    window.location.replace(getQrConnectAuthUrl(loginState, corpId, agentId))
  } else {
    window.location.replace(generateOAuthURL(loginState, corpId, agentId))
  }
}


/**
 * 获取企业应用的信息
 */
export const handleAuth = function () {
  setLocalStorage('corpId', 'ww774eb8b9292728f2')
  setLocalStorage('appId', '1000008')
  setLocalStorage('agentId', '1000008')

  return {
    agentId: 1000008,
    corpId: 'ww774eb8b9292728f2',
    appId: 'ww774eb8b9292728f2'
  }

  // console.log(111111111111)
  // return new Promise((resolve, reject) => {

  // })
  // {
  //   agentId: 1000008,
  //   corpId: 'ww774eb8b9292728f2',
  //   appId: 'ww774eb8b9292728f2'
  // }
  // return axios(applicationInfoData)
  //   .then(res => {
  //     const {
  //       data: { data, statusCode, message = '' }
  //     } = res

  //     if (statusCode === 200) {
  //       const { corpId, agentId, appId, defendFlag } = data

  //       setLocalStorage('corpId', corpId)
  //       setLocalStorage('appId', agentId)
  //       setLocalStorage('appId', appId)
  //       setLocalStorage('defendFlag', defendFlag)

  //       return data
  //     } else {
  //       window.projectApp.$toast({
  //         message,
  //         type: 'fail'
  //       })
  //       router.push({ name: 'error-page', query: { tip: message } })
  //     }
  //   })
}

/**
 * @description 调起微信弹窗授权
 * @returns
 */
export const getWxAuthUrl = () => {
  const redirect = filterUrlParams()
  return `https://${window.projectConf.domain}/connect/oauth2/authorize?appid=${
    getLocalStorage('appId')
  }&redirect_uri=${redirect}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`
}

// 过滤/覆盖URL中的字段
const filterUrlParams = () => {
  const obj = new URLSearchParams(window.location.search)

  const query = []
  for (const arr of obj.entries()) {
    // 过滤code与state, deviceId参数
    if (!['code', 'state'].includes(arr[0].toLowerCase())) {
      query.push(arr.join('='))
    }
  }

  return encodeURIComponent(location.origin + location.pathname + (query.length > 0 ? `?${query.join('&')}` : ''))
}

/**
 * @description 判断是不是企微浏览器
 * @returns
 */
export const isWxBrowser = () => {
  const ua = navigator.userAgent.toLowerCase()
  const uaWx = ua.match(/MicroMessenger/i)
  const uaQywx = ua.match(/WxWork/i)
  const isWx = uaWx ? uaWx[0] === 'micromessenger' : false
  const isWxWork = uaQywx ? uaQywx[0] === 'wxwork' : false
  return {
    isWx: isWxWork ? false : isWx,
    isWxWork
  }
}
